package unimelb.distSystems.project2;

import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import unimelb.distSystems.communications.CORBA.ServiceMatchRoom;

/*
 * Subclass of GUIScreen for creating and hosting a new match room
 */
public class HostRoomScreen extends GUIScreen {
	/*
	 * GUI components
	 */
	private JTextField roomname_tf = new JTextField(30);
	private JLabel roomname_text = new JLabel("Name of your match room");
	private JButton host_button = new JButton("Host this match room");
	private JButton cancel_button = new JButton("Cancel");
	private JLabel trackpic_text = new JLabel("Track preview");
	private JLabel track_text = new JLabel("Track to use");
	private DefaultListModel track_textlist = new DefaultListModel();
	private JList tracklist_container = new JList(track_textlist);
	private JLabel numplayer_text = new JLabel("Maximum number of players");
	private JLabel title_text = new JLabel("Host a new match room");
	private JComboBox num_player_cbox = new JComboBox();
	private ImagePanel trackpic_panel = new ImagePanel(null);
	
	private Game client;

	/*
	 * Constructor
	 */
	public HostRoomScreen(Game client) {
		super();
		this.client=client;
		initialise_listeners(client);
		
		for(int i=2;i<=Configurations.max_players;i++)
			num_player_cbox.addItem(i);
		
		for(int i=0;i<Configurations.tracks.length;i++)
		{
			int track_id=Integer.parseInt(Configurations.tracks[i][0]);
			ListItem item = new ListItem(track_id, Configurations.tracks[i][1]);
			track_textlist.addElement(item);
		}
		
		tracklist_container.setFont(new Font(null,Font.BOLD,14));
		tracklist_container.setSelectedIndex(0);		
		
		title_text.setFont(new Font(null,Font.BOLD,30));
		
		roomname_tf.setPreferredSize(new Dimension(260,30));
	}

	/*
	 * @see unimelb.distSystems.project2.GUIScreen#perform_actions_prior_display()
	 */
	public void perform_actions_prior_display() {
		tracklist_container.setSelectedIndex(0);
		num_player_cbox.setSelectedIndex(0);
		roomname_tf.setText("");
	}
	
	/*
	 * @see unimelb.distSystems.project2.GUIScreen#perform_actions_prior_exit()
	 */
	public void perform_actions_prior_exit()
	{
		//Do nothing
	}
	
	/*
	 * @see unimelb.distSystems.project2.GUIScreen#display(java.awt.Container)
	 */
	public void display(Container screen_container) {
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.HORIZONTAL;
		screen_container.setLayout(new FlowLayout());
		
		JPanel title_p = new JPanel();
		title_p.setLayout(new GridBagLayout());
		title_p.add(title_text);
		screen_container.add(title_p);
		
		JPanel main_p = new JPanel();
		main_p.setLayout(new GridBagLayout());
		screen_container.add(main_p);
		
		c.gridx = 0;
		c.gridy = 0;
		c.gridwidth = 2;
		main_p.add(roomname_text,c);
		
		c.gridx = 0;
		c.gridy = 1;
		main_p.add(roomname_tf,c);
		
		c.gridx = 0;
		c.gridy = 2;
		main_p.add(blank,c);
		
		c.gridx = 0;
		c.gridy = 3;
		main_p.add(numplayer_text,c);
		
		c.gridx = 0;
		c.gridy = 4;
		main_p.add(num_player_cbox,c);
		
		c.gridx = 0;
		c.gridy = 5;
		main_p.add(blank2,c);
		
		c.gridx = 0;
		c.gridy = 6;
		main_p.add(track_text,c);
		
		JScrollPane scroll_p = new JScrollPane(tracklist_container);
		c.gridx = 0;
		c.gridy = 7;
		main_p.add(scroll_p,c);
		
		c.gridx = 0;
		c.gridy = 8;
		main_p.add(blank3,c);
		
		c.gridx = 0;
		c.gridy = 9;
		c.gridwidth = 1;
		main_p.add(host_button,c);
		
		c.gridx = 1;
		c.gridy = 9;
		main_p.add(cancel_button,c);
		
		c.gridx = 3;
		c.gridy = 0;
		c.insets=new Insets(0,20,0,0);
		main_p.add(trackpic_text,c);

		c.gridx = 3;
		c.gridy = 1;
		c.gridheight = 9;
		c.ipadx=trackpic_panel.getImageWidth();
		c.ipady=trackpic_panel.getImageHeight();
		main_p.add(trackpic_panel,c);
	}

	/*
	 * @see unimelb.distSystems.project2.GUIScreen#initialise_listeners(unimelb.distSystems.project2.Game)
	 */
	protected void initialise_listeners(final Game client) {
		/*
		 * Leave the screen
		 */
		cancel_button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				client.go_to_screen(Game.MENU_SCREEN);
			}
		});
		
		/*
		 * Change the track preview whenever human changes the track in the track list
		 */
		tracklist_container.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent evt) {
				trackpic_panel.load_new_image(Configurations.tracks[tracklist_container.getSelectedIndex()][2]);
			}
		});
		
		/*
		 * Create new match room and go into it
		 */
		host_button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(valid_all())
				{
					String name=roomname_tf.getText().trim();
					int max_players=num_player_cbox.getSelectedIndex()+2;
					long track_id=((ListItem)track_textlist.get(tracklist_container.getSelectedIndex())).getID();
					long matchroom_id;
					boolean success=false;
	
					////////////////////////////////////
					//COBRA COMMUNICATION
					////////////////////////////////////
					//Pass the match_room object & player ID to GameServer and get the success status
					MatchRoom new_matchroom = new MatchRoom(name, max_players, track_id,client.get_current_player().getPlayerID());
                    
					ServiceMatchRoom room = new_matchroom.getServiceMatchRoom();
                    matchroom_id = client.getGameService().createRoom(room);
                    
                    if(matchroom_id != -1){
                    	//Get the latest copy of the room from server based on ID
                    	room = client.getGameService().getMatchRoom(matchroom_id);
                    	System.out.println("New match room ID: "+room.matchroom_id);

                    	////////////////////////////////////
						//COBRA COMMUNICATION
						////////////////////////////////////
						//Tell the server that host joined this matchroom
                        client.getGameService().joinGame(matchroom_id, client.get_current_player().getPlayerID());
                        
                        client.cache_match_room(new MatchRoom(room));//overwrite
                        success=true;
                    } else {
                        success=false;
                    }
					
					if(success)
					{
						JOptionPane.showMessageDialog(null,"Your match room is successfully created.",
								"Success",JOptionPane.INFORMATION_MESSAGE);
						client.go_to_screen(Game.MATCHROOM_SCREEN);
					}
					else
					{
						JOptionPane.showMessageDialog(null,"The server is unable to host more match rooms or there is an existing match room with your match room name.",
								"Error",JOptionPane.ERROR_MESSAGE);
					}
				}
			}
		});
	}
	
	/*
	 * Check that all inputs are good
	 */
	private boolean valid_all()
	{
		String matchroom_name=roomname_tf.getText().trim();
		
		if(matchroom_name.equals(""))
		{
			JOptionPane.showMessageDialog(null,"Match room name field is empty!",
					"Error",JOptionPane.ERROR_MESSAGE);
			return false;
		}
		
		return true;
	}
}
